<template>
  <base-breadcrumb :title="titleName">
    <searchData
      :search-data="searchArr"
      @search="search"
    />

    <a-card :bordered="false">
      <div class="table-operator">
        <a-button
          v-btnPermission="[{code:'seex_pm_005_add_01',ident:'prma_seex'},{code:'buco_pm_005_add_01',ident:'prma_buco'}]"
          type="primary"
          icon="plus"
          @click="handleAdd"
        >
          新增项目类型
        </a-button>
        <a-button @click="handleDel" v-btnPermission="'pm_005_del_04'">
          删除
        </a-button>
      </div>
      <div class="pub-table-select-count">
        <a-icon type="info-circle" theme="twoTone" />
        <span style="margin-right: 12px">共计：<span class="totalNum">{{total}}个</span> | 已选择<span class="totalNum">{{ids.length}}个</span></span>
      </div>

      <list-table
        ref="table"
        size="default"
        :row-key="record=>record.typeId"
        :columns="columns"
        :request="loadData"
        :alert="true"
        :isFixedRight="false"
        show-size-changer
        show-quick-jumper
        :row-selection="rowSelection"
        show-pagination="auto"
      >
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>
        <!-- <span
          slot="constructionScope"
          slot-scope="text, record, index"
        >
        {{record.constructionScope?record.constructionScope:'无'}}
      </span> -->
        <span
          slot="action"
          slot-scope="text, record"
        >
          <MoreButton>
            <a
              v-btnPermission="'pm_005_loo_02'"
              @click="handleSub(record)"
            >查看</a>
            <a
              v-btnPermission="'pm_005_edi_03'"
              @click="handleEdit(record)"
            >编辑</a>
          </MoreButton>
        </span>
      </list-table>

      <add-type
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      />

      <find-type
        :visible="visibles"
        :loading="confirmLoading"
        :model="mdls"
        @cancel="handleCancels"
      />
    </a-card>
  </base-breadcrumb>
</template>

<script>
  import moment from 'moment'
  import { getProjectypesList, addProjectypes, editProjectypes, getCalType, delProjectypes } from '@/api/project/projectypes'
  import addType from './addType'
  import findType from './findType'

  const columns = [
    {
      title: '序号',
      scopedSlots: { customRender: 'serial' }
    },
    {
      title: '类型名称',
      dataIndex: 'typeName'
    },
    {
      title: '面积计算/长度计算',
      dataIndex: 'calculateType',

    },
    {
      title: '主施工范围',
      dataIndex: 'constructionScope',
      // scopedSlots: { customRender: 'constructionScope' }
    },
    {
      title: '状态',
      dataIndex: 'typeStatus',
      scopedSlots: { customRender: 'typeStatus' }
    },
    {
      title: '操作',
      dataIndex: 'action',
      scopedSlots: { customRender: 'action' }
    }
  ]

  const statusMap = {
    0: {
      status: 'default',
      text: '关闭'
    },
    1: {
      status: 'processing',
      text: '运行中'
    },
    2: {
      status: 'success',
      text: '已上线'
    },
    3: {
      status: 'error',
      text: '异常'
    }
  }

  export default {
    name:'a'+Date.now(),
    components: {
      addType,
      findType
    },
    data() {
      this.columns = columns
      return {
        searchArr: [
          // 搜索框
          {
            name: '类型名称',
            value: 'typeName',
            type: 'input'
          },
          {
            name: '计算方式',
            value: 'computeMode',
            type: 'select',
            data:[
              {
                value: '',
                label: '全部'
              },
              {
                value: '0',
                label: '面积计算'
              },
              {
                value: '1',
                label: '长度计算'
              }
            ]
          },
          {
            name:'状态',
            value:'typeStatusCode',
            type:'select',
            data:[
              {
                value: '',
                label: '全部'
              },
              {
                value: '1',
                label: '可用'
              },
              {
                value: '0',
                label: '不可用'
              }
            ],
          }
        ],
        titleName:'',
        // create model
        visible: false,
        visibles: false,
        confirmLoading: false,
        mdl: null,
        mdls: null,

        ids:[],
        total: 0,
        // 高级搜索 展开/关闭
        advanced: false,
        // 查询参数
        queryParam: {},
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          const requestParameters = Object.assign({}, parameter, this.queryParam)
          return getProjectypesList(requestParameters)
            .then(res => {
              this.total = res.totalSize;
              return res
            })
        },
        selectedRowKeys: [],
        selectedRows: [],
        isEdit:false,
        cacheSelecRows: []
      }
    },
    filters: {
      statusFilter(type) {
        return statusMap[type].text
      },
      statusTypeFilter(type) {
        return statusMap[type].status
      }
    },
    created() {
      this.getCalType()
    },
    computed: {
      rowSelection() {
        return {
          selectedRowKeys: this.selectedRowKeys,
          selectedRows: this.selectedRows,   // 当前行所有数据
          onChange: this.onSelectChange
        }
      }
    },
    methods: {
      search(values){
        this.queryParam = values
        this.$refs.table.refresh(true)
      },
      getCalType(){
        getCalType().then(res=>{
          let arrys = res.data
          this.searchArr[1].data = this.getLabelData(arrys)
        })
      },
      searchData(){  // 搜索
        let _this = this;
        _this.$refs.table.refresh(true)
      },
      deletes(){},
      handleAdd() {
        this.mdl = null
        this.confirmLoading = false
        this.visible = true
        this.isEdit = false
      },
      handleDel(){
        let that = this
        if(that.selectedRows.length == 0){
          that.$message.error('请先选择删除的项目类型！')
          return
        }
        that.$confirm({
          title: '删除',
          content: '确定删除项目类型吗？',
          onOk() {
            delProjectypes({ids:that.ids}).then(res=>{
              if(res.data == 200 || res.data.code == 200){
                that.$message.success('删除成功！')
                that.$refs.table.refresh(true)
                that.selectedRows = []
                that.selectedRowKeys = []
              }
            })
          },
          onCancel() {},
        });

      },

      handleEdit(record) {
        this.visible = true
        this.mdl = { ...record }
        this.isEdit = true
      },
      transformationData(data) {
        data = JSON.parse(JSON.stringify(data))
        if(data.length === 0) {
          this.$message.error('请输入主施工范围');
          return false
        }
        let empty = data.findIndex((item)=> {
          return item.scope === '';
        })
        if(empty !== -1) {
          this.$message.error('主施工范围不能包含空');
          return false
        }
        if(this.mdl && this.mdl.scopeList?.length > 0) {
          let scopeList = this.mdl.scopeList;
          data.map(item=> {
            if(scopeList.findIndex((i) => { return item.id === i.id}) === -1) {//添加的类型
              item.operationType = 'ADD';
            }
            if(scopeList.findIndex((i) => { return item.id === i.id && item.scope !== i.scope}) !== -1) {//编辑的类型
              item.operationType = 'UPDATE';
            }
          })
          scopeList.map((item)=> {
            if(data.findIndex((i) => { return item.id === i.id}) === -1) {
              item.operationType = 'DELETE';
              data.push(item);
            }
          })
        }else {
          data.map(item=> {
            item.operationType = 'ADD'
          })
        }
        return data
      },
      handleOk() {
        let that = this;
        const form = that.$refs.createModal.form
        form.validateFields((errors, values) => {
          if (!errors) {
            let scopeList = that.transformationData(that.$refs.createModal.data);
            scopeList.map(item=>{item.id = item.id.indexOf('id') !== -1 ? null : item.id});
            if(!scopeList) return;
            if ( that.isEdit == true) {
              // 修改
              that.mdl.typeName = values.typeName
              that.mdl.calculateTypeCode = values.calculateTypeCode
              that.mdl.typeStatusCode = values.typeStatusCode
              that.mdl.scopeList = scopeList
              that.confirmLoading = true
              editProjectypes(that.mdl).then(res=>{
                that.confirmLoading = false
                if(res.data.code==200){
                  that.visible = false

                  // 重置表单数据
                  form.resetFields()
                  // 刷新表格
                  that.$refs.table.refresh(true)

                  that.$message.success('修改成功！')
                }else{
                  that.$message.error('修改失败！ ')
                  that.visible = false
                  form.resetFields()

                }

              }).catch(()=>{
                that.confirmLoading = false
              })

            } else {
              // 新增
              that.confirmLoading = true
              values.scopeList = scopeList
              addProjectypes(values).then(res=>{
                that.confirmLoading = false
                if(res.code == 200){
                  that.visible = false
                  // 重置表单数据
                  form.resetFields()
                  // 刷新表格
                  that.$refs.table.refresh(true)
                  that.$message.success('新增成功！')
                }else{
                  that.$message.error('新增失败！')
                  // 重置表单数据
                  form.resetFields()
                  that.visible = false
                }

              }).catch(()=>{
                that.confirmLoading = false
              })

            }
          }
        })
      },
      handleCancel() {
        this.visible = false
        const form = this.$refs.createModal.form
        form.resetFields() // 清理表单数据（可不做）
      },
      handleSub(record) {
        this.visibles = true
        this.mdls = { ...record }
      },
      handleCancels() {
        this.visibles = false
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        const arr2 =  this.setTableListTopNum(this.cacheSelecRows, selectedRowKeys, selectedRows, 'typeId')
        this.cacheSelecRows= arr2;
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows =  this.cacheSelecRows

        let arr = []
        this.selectedRows.forEach(function(obj,i) {
          arr.push(obj.typeId)
        })
        this.ids = arr
      },
      toggleAdvanced() {
        this.advanced = !this.advanced
      },
      resetSearchForm() {
        this.queryParam = {
          date: moment(new Date())
        }
      }
    }
  }
</script>


